import jwt
from django.conf import settings
from rest_framework.response import Response
from jwt import exceptions
from users.models import User


def check_login(func):
    def wrapper(self, request, *args, **kwargs):
        # 1.获取token
        token = request.headers.get('token')
    # 2.根据token判断用户是否登录
    # 已登录 ，则获取payload中的username ，根据用户查询对象
    # 未登录， 直接返回响应未登录
        try:
            payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms='HS256')
        except exceptions.ExpiredSignature:
            return Response({"code": 204, 'msg': '历史签名过期，需重新登录'})

        except exceptions.DecodeError:
            return Response({"code":205, 'msg':'非法的token'})

        # 3. 根据productID查询商品对象
        username = payload.get('username')
        user = User.objects.get(username=username)
        request.user = user

        # 参数func的执行
        return func(self, request, *args, **kwargs)
    return wrapper